#include <iat/iat.h>

/* wav音频头部格式 */
typedef struct _wave_pcm_hdr
{
	char            riff[4];                // = "RIFF"
	int		size_8;                 // = FileSize - 8
	char            wave[4];                // = "WAVE"
	char            fmt[4];                 // = "fmt "
	int		fmt_size;		// = 下一个结构体的大小 : 16

	short int       format_tag;             // = PCM : 1
	short int       channels;               // = 通道数 : 1
	int		samples_per_sec;        // = 采样率 : 8000 | 6000 | 11025 | 16000
	int		avg_bytes_per_sec;      // = 每秒字节数 : samples_per_sec * bits_per_sample / 8
	short int       block_align;            // = 每采样点字节数 : wBitsPerSample / 8
	short int       bits_per_sample;        // = 量化比特数: 8 | 16

	char            data[4];                // = "data";
	int		data_size;              // = 纯数据长度 : FileSize - 44 
} wave_pcm_hdr;

/* 默认wav音频头部数据 */
wave_pcm_hdr default_wav_hdr = 
{
	{ 'R', 'I', 'F', 'F' },
	0,
	{'W', 'A', 'V', 'E'},
	{'f', 'm', 't', ' '},
	16,
	1,
	1,
	16000,
	32000,
	2,
	16,
	{'d', 'a', 't', 'a'},
	0  
};

Iat * Iat::m_instance = nullptr;
Iat::Iat():
    Config("resource/config/msc.json",true),
    IAgentComponent(AgentComponentType::SPEECH,false){
    m_instance = this;
}
void Iat::BeforeEnd(){
	getRoot()["panel_show"] = panel_show;
	getRoot()["startWhenEnd"] = startWhenEnd;
}
Iat::~Iat(){
    //sr_stop_listening(&iat);
    //sr_uninit(&iat);
	//can't uninit here , because it may be called by internal
    MSPLogout();
}
void Iat::Init(){
	panel_show = getValue("panel_show").asBool();
    startWhenEnd = getValue("startWhenEnd").asBool();
	quiet = getValue("quiet").asBool();
    MSPLogin(NULL, NULL, login_params);
	if(startWhenEnd)StartRecord();
}
void Iat::StartRecord(){
    sr_init(&iat, session_begin_params_stt, SR_MIC, &recnotifier);
    cout<<sr_start_listening(&iat)<<endl;
    record_ok = false;
}
void Iat::EndRecord(){
    record_ok = true;
    sr_stop_listening(&iat);
    sr_uninit(&iat);
}
void Iat::on_result(const char *result, char is_last){
    static string s;
    s += result;
    if(is_last){
        cout<<s<<endl;
		m_instance->message_sum.append(s+"\n");
		m_instance->SendMessage("STTOK",s);
        s.clear();
    }
}
void Iat::on_speech_begin(){
	//m_instance->record_ok = false;
}
void Iat::on_speech_end(int reason){
	//m_instance->record_ok = true;
	cout<<reason<<endl;
    vector<string> content = {"IATEND"};
    m_instance->agent->PushMessage(Message(AgentComponentType::SPEECH,content));
}
void Iat::Update(){
	if(!panel_show)return;
	static char inputText[1024] = "你好，我是未来人工智能机器人";
    ImGui::Begin("MSC Controller");
	ImGui::Checkbox("自动开始",&startWhenEnd);
	ImGui::SameLine();
	ImGui::Checkbox("保持安静",&quiet);
    if(ImGui::Button(record_ok?"开始":"结束")){
        if(record_ok){
            StartRecord();
        }else{
            EndRecord();
        }
    }
    ImGui::InputTextMultiline("输入文本",inputText,sizeof(inputText),ImVec2(-1.0f, ImGui::GetTextLineHeight() * 8));
	ImGui::Text(message_sum.c_str());
    if(ImGui::Button("合成",ImVec2(-1.0f, 0.0f))){
        TextToSpeech_Sync(inputText);
    }
    ImGui::End();
}
void Iat::PollMessage(Message message){
    if(message.fromType == AgentComponentType::SPEECH
        && message.content.at(0) == "IATEND")
        if(startWhenEnd)StartRecord();
	if(message.fromType == AgentComponentType::NLP)
		if(message.content.at(0) == "commonRet")
			if(!quiet)TextToSpeech_Sync(message.content.at(1));
	if(message.fromType == AgentComponentType::AUDIO){
		string type = message.content.at(0);
		if(type == "StartPlay")EndRecord();
		else if(type == "EndPlay" && startWhenEnd)StartRecord();
	}
	if(message.fromType == AgentComponentType::GUI){
		string type = message.content.at(0);
		if(type == "OPEN_SPEECH")panel_show = true;
	}
}
bool Iat::TextToSpeech_Sync(string text,string filePath,bool endLast){
	if(thd_tts.joinable() == false){
        if(!tts_ok && !endLast) return false;
        else{
            tts_ok = false;
            thd_tts = thread(&Iat::TextToSpeech_Async,this,text,filePath);
            thd_tts.detach();
        }
    }else return false;
}
void Iat::TextToSpeech_Async(string text,string filePath){
    int          ret          = -1;
	FILE*        fp           = NULL;
	const char*  sessionID    = NULL;
	unsigned int audio_len    = 0;
	wave_pcm_hdr wav_hdr      = default_wav_hdr;
	int          synth_status = MSP_TTS_FLAG_STILL_HAVE_DATA;
	fp = fopen(filePath.c_str(), "wb");
	/* 开始合成 */
	sessionID = QTTSSessionBegin(session_begin_params_tts, &ret);
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSSessionBegin failed, error code: %d.\n", ret);
		fclose(fp);
        return;
	}
	ret = QTTSTextPut(sessionID, text.c_str(), text.length(), NULL);
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSTextPut failed, error code: %d.\n",ret);
		QTTSSessionEnd(sessionID, "TextPutError");
		fclose(fp);
		return;
	}
	printf("正在合成 ...\n");
	fwrite(&wav_hdr, sizeof(wav_hdr) ,1, fp); //添加wav音频头，使用采样率为16000
	while (1)
	{
		/* 获取合成音频 */
		const void* data = QTTSAudioGet(sessionID, &audio_len, &synth_status, &ret);
		if (MSP_SUCCESS != ret)
			break;
		if (NULL != data)
		{
			fwrite(data, audio_len, 1, fp);
		    wav_hdr.data_size += audio_len; //计算data_size大小
		}
		if (MSP_TTS_FLAG_DATA_END == synth_status)
			break;
		printf(">");
		usleep(150*1000); //防止频繁占用CPU
	}
	printf("\n");
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSAudioGet failed, error code: %d.\n",ret);
		QTTSSessionEnd(sessionID, "AudioGetError");
		fclose(fp);
		return;
	}
	/* 修正wav文件头数据的大小 */
	wav_hdr.size_8 += wav_hdr.data_size + (sizeof(wav_hdr) - 8);
	
	/* 将修正过的数据写回文件头部,音频文件为wav格式 */
	fseek(fp, 4, 0);
	fwrite(&wav_hdr.size_8,sizeof(wav_hdr.size_8), 1, fp); //写入size_8的值
	fseek(fp, 40, 0); //将文件指针偏移到存储data_size值的位置
	fwrite(&wav_hdr.data_size,sizeof(wav_hdr.data_size), 1, fp); //写入data_size的值
	fclose(fp);
	fp = NULL;
	/* 合成完毕 */
	ret = QTTSSessionEnd(sessionID, "Normal");
	if (MSP_SUCCESS != ret)
	{
		printf("QTTSSessionEnd failed, error code: %d.\n",ret);
	}

	SendMessage("TTSOK",filePath);
}
void Iat::SendMessage(string type,string result){
    vector<string> content = {type,result};
    agent->PushMessage(Message(AgentComponentType::SPEECH,content));
}